import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { DatePipe } from '@angular/common';
import { CommonService } from 'src/app/services-common/common.service';
import { FinanceCustomizedManageService } from '../finance-customized-manage.service';

@Component({
  selector: 'app-pay-customized-coupons',
  templateUrl: './pay-customized-coupons.component.html',
  styleUrls: ['./pay-customized-coupons.component.scss'],
  providers: [DatePipe]
})
export class PayCustomizedCouponsComponent implements OnInit {

  searchParams: any = {
    oddNumbers: '', // 综合搜素
    beginTime: '',
    endTime: ''
  };
  payDates: any = [];

  tableParams = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };
  tableData: any = [];

  // Export Table
  exportLoading: boolean = false;

  constructor(
    private message: NzMessageService,
    private datePipe: DatePipe,
    private commonService: CommonService,
    private services: FinanceCustomizedManageService
  ) { }

  ngOnInit(): void {
    this.loadTable()
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.tableLoading = true;
    const res: any = await this.services.buyCustomCouponList(params);
    this.tableParams.tableLoading = false;

    if (res.code == 0) {
      const { records, total } = res.data || {};
      this.tableData = records || [];
      this.tableParams.total = total || 0;
    } else {
      this.tableData = [];
      this.tableParams.total = 0;
      this.message.error(res.message);
    }
  }

  searchData() {
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData() {
    for (let key in this.searchParams) {
      this.searchParams[key] = '';
    }
    this.payDates = [];
    this.tableParams.page = 1;
    this.loadTable();
  }

  dateChange(result: any) {
    this.searchParams.beginTime = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd') : '';
    this.searchParams.endTime = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd') : '';
  }

  async exportTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: 1000000
    }
    this.exportLoading = true;
    const res: any = await this.services.exportCustomCouponData(params);
    this.exportLoading = false;
    if (res.type == 'application/octet-stream') {
      this.commonService.downLoadBlobFile(res, '购买定制券');
    } else {
      this.message.error('导出失败');
    }
  }

  // Change PageIndex
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  // Change PageSize
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }
}
